
from google.appengine.ext.db import Key

from dbmodels.faction import FactionModel

from protorpc import message_types
from protorpc import messages
from protorpc import remote

package = "api"

class Faction(messages.Message):
    name = messages.StringField(1, required=True)
    label = messages.StringField(2, required=True)
    icon = messages.StringField(3, required=False)
    units = messages.StringField(4, repeated=True)

''' Faction response element '''
class Factions(messages.Message):
    factions = messages.MessageField(Faction, 1, repeated=True)

class FactionService(remote.Service):

    @remote.method(message_types.VoidMessage, Factions)
    def list(self, request):
        factions = []
        for dbFaction in FactionModel.all():
            factions.append(Faction(name=dbFaction.name, label=dbFaction.label))

        return Factions(factions=factions)

    @remote.method(Faction, message_types.VoidMessage)
    def add(self, request):
        faction = FactionModel(key_name=request.name, name=request.name, label=request.label, icon=request.icon)
        for unit in request.units:
            # These are keys, do add their key references
            k = Key.from_path('UnitModel', unit)
            faction.units.append(k)
        faction.put()
        return message_types.VoidMessage()
